package com.novel.authorization.security.satoken;

import cn.dev33.satoken.SaManager;
import cn.dev33.satoken.stp.StpInterface;
import cn.dev33.satoken.stp.StpUtil;
import com.novel.authorization.staff.service.NfGroupService;
import com.novel.authorization.staff.vo.UserInfoVO;
import com.novel.base.constants.CommonConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 自定义权限验证接口扩展
 *
 * @author 樊温军
 * @date 2025/5/8 下午3:47
 */
@Component
public class StpInterfaceImpl implements StpInterface {

    @Resource
    private NfGroupService nfGroupService;

    /**
     * 返回一个账号所拥有的权限码集合
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        SaManager.getLog().debug("权限码参数：loginId={}, loginType={}", loginId, loginType);
        List<String> perms = new ArrayList<>();
        try {
            UserInfoVO userInfoVO = (UserInfoVO) StpUtil.getSession().get(CommonConstants.USER_SESSION_KEY);
            if (userInfoVO != null) {
                userInfoVO.getGroups().forEach(group -> {
                    group.getPerms().forEach(perm -> {
                        perms.add(perm.getCode());
                    });
                });
            }
        } catch (Exception e) {
            SaManager.getLog().error("权限码获取异常：{}", e.getMessage());
        }
        if (!CollectionUtils.isEmpty(perms)) {
            return perms;
        }
        return nfGroupService.getPermissionList(loginId);
    }

    /**
     * 返回一个账号所拥有的角色标识集合 (权限与角色可分开校验)
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        SaManager.getLog().debug("角色标识参数：loginId={}, loginType={}", loginId, loginType);
        List<String> roles = new ArrayList<>();
        try {
            UserInfoVO userInfoVO = (UserInfoVO) StpUtil.getSession().get(CommonConstants.USER_SESSION_KEY);
            if (userInfoVO != null) {
                userInfoVO.getGroups().forEach(group -> {
                    roles.add(group.getCode());
                });
            }
        } catch (Exception e) {
            SaManager.getLog().error("用户组获取异常：{}", e.getMessage());
        }
        if (!CollectionUtils.isEmpty(roles)) {
            return roles;
        }
        return nfGroupService.getRoleList(loginId);
    }

}

